<?php

	function parseLink($node, $domain, $attribute)
	{
		if(stristr($node->getAttribute($attribute), "http") === FALSE)
		{
			$node->setAttribute($attribute, "http://" . $domain . $node->getAttribute($attribute));
		}
		
		if(stristr($_SERVER["SERVER_NAME"], 'localhost') === FALSE)
		{
			$node->setAttribute($attribute, "http://proxy.monkelabs.com/index.php?url=" . $node->getAttribute($attribute));
		}else
		{
			$node->setAttribute($attribute, "http://localhost/proxy/index.php?url=" . $node->getAttribute($attribute));	
		}	
	}
		
	function parseImg($node, $domain, $path, $attribute)
	{
		if(stristr($node->getAttribute($attribute), "http") === FALSE)
		{
			// TODO: make this work
			if(substr($node->getAttribute($attribute), 0, 1) == "\\")
			{
				$node->setAttribute($attribute, "http://" . $domain . $node->getAttribute($attribute));
			}else
			{
				$node->setAttribute($attribute, "http://" . $domain . $path . $node->getAttribute($attribute));
			}
		}
	}

	if(isset($_GET["url"]))
	{
		$url = $_GET["url"];
		
		// check to see if this url needs the http apended to it
		/*if(preg_match("^(http:\/\/).+$", $url))
		{
			$url = "http://" . $url;
		}*/
		
		// now we need to parse href, src and action attributes to make sure they post to the proxy too

		$uri = parse_url($url);
		
		$document = new DOMDocument();
		
		@$document->loadHTMLFile($url);
		
		// to the links
		
		$anchors = $document->getElementsByTagName("a");
		$links = $document->getElementsByTagName("link");
		$imgs = $document->getElementsByTagName("img");
		$scripts = $document->getElementsByTagName("script");
		
		// loop over all the link items and update their links to point through the proxy
		foreach ($anchors as $anchor) {
			
			parseLink($anchor, $uri["host"], "href");	
		}
		
		foreach($links as $link)
		{
			parseImg($link, $uri["host"], $uri["path"], "href");	
		}
		
		foreach($imgs as $img)
		{
			parseImg($img, $uri["host"], $uri["path"], "src");	
		}
		
		foreach($scripts as $script)
		{
			parseImg($script, $uri["host"], $uri["path"], "src");	
		}
		
		// dump the output to the screen
		echo $document->saveHTML();
		
		
		
	}else
	{
		// just dump out the welcome form
		echo file_get_contents("form.html");	
	}


?>
